package curator.dwj.cn;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.BackgroundCallback;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.framework.api.CuratorEventType;
import org.apache.curator.retry.RetryUntilElapsed;
import org.apache.zookeeper.data.Stat;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by Administrator on 2017/11/14 0014.
 */
public class CheckExists {
    public static void main(String[] args) throws Exception {

        ExecutorService es = Executors.newFixedThreadPool(5);//线程池

        //RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        //RetryPolicy retryPolicy = new RetryNTimes(5, 1000);
        RetryPolicy retryPolicy = new RetryUntilElapsed(5000, 1000);

        //CuratorFramework client = CuratorFrameworkFactory.newClient("192.168.110.134:2181", 5000, 5000, retryPolicy);
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString("192.168.110.134:2181")
                .sessionTimeoutMs(5000)
                .connectionTimeoutMs(5000)
                .retryPolicy(retryPolicy)
                .build();
        client.start();

        Stat stat = client.checkExists().forPath("/dwj/1");
        System.out.println(stat);

        //如果异步调用
        client.checkExists().inBackground(new BackgroundCallback() {
            public void processResult(CuratorFramework curatorFramework, CuratorEvent curatorEvent) throws Exception {
                Stat stat = curatorEvent.getStat();
                CuratorEventType t = curatorEvent.getType();//事件类型
                int r = curatorEvent.getResultCode();
                //异步调用会放到一个单独的线程中执行，可以使用线程池实现
                Object o = curatorEvent.getContext();
                curatorEvent.getPath();
                curatorEvent.getChildren();
                curatorEvent.getData();

            }
        },"123", es).forPath("/dwj/1");
        Thread.sleep(Integer.MAX_VALUE);
    }
}
